﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Xml.Serialization;

namespace Utilities
{
    public class Serialization
    {
        public enum FormatType
        {
            Binary,Soap,XML
        }
        public static void serialize<T>(string path, T obj,FormatType type)
        {
            IFormatter formatter=null;
            switch (type)
            {
                case FormatType.Binary:
                    formatter = new BinaryFormatter();
                    break;
                case FormatType.Soap:
                    formatter = new SoapFormatter();
                    break;
                case FormatType.XML:
                    XmlSerializer ser = new XmlSerializer(typeof(T));
                    TextWriter writer = new StreamWriter(path);
                    ser.Serialize(writer, obj);
                    writer.Close();
                    return;
            }
             
            Stream stream = new FileStream(path,FileMode.Create,FileAccess.Write, FileShare.None);
            formatter.Serialize(stream, obj);
            stream.Close();
        }
        public static T deserialize<T>(string path, FormatType type)
        {
            IFormatter formatter = null;
            switch (type)
            {
                case FormatType.Binary:
                    formatter = new BinaryFormatter();
                    break;
                case FormatType.Soap:
                    formatter = new SoapFormatter();
                    break;
                case FormatType.XML:
                    XmlSerializer mySerializer = new XmlSerializer(typeof(T));
                    FileStream myFileStream = new FileStream(path, FileMode.Open);
                    T obj = (T)mySerializer.Deserialize(myFileStream);
                    myFileStream.Close();
                    return obj;
            }
            Stream stream = new FileStream(path,
                                      FileMode.Open,
                                      FileAccess.Read,
                                      FileShare.Read);
            T dobj = (T)formatter.Deserialize(stream);
            stream.Close();
            return dobj;
        }
    }
}
